<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px"
      style="width: 90%; margin-left:50px;">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="名称" prop="dataProcessName">
            <el-input v-model="temp.dataProcessName" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据源" prop="sourceId">
            <el-select v-model="temp.sourceId" placeholder="请选择数据源"  @change="choseSource">
              <el-option v-for="source in sourceOptions" :key="source.id" :label="source.sourceName" :value="source.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源表" prop="sourceTableName" >
            <el-select v-model="temp.sourceTableName" placeholder="请选择来源表" @change="choseSourceTable">
              <el-option v-for="item in taleList" :key="item.id" :label="item.tableName" :value="item.tableName" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标表" prop="targetTableName" >
            <el-select v-model="temp.targetTableName" placeholder="请选择目标表" @change="choseTargetTable">
              <el-option v-for="source in taleList" :key="source.id" :label="source.tableName" :value="source.tableName" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行类型" prop="executeName">
            <el-select v-model="temp.executeName" class="filter-item" placeholder="请选择执行类型" @change="choseType">
              <el-option v-for="item in dictList('executor_type')" :key="'type' + item.label" :label="item.label"
                :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行参数" prop="executeParams" v-show="temp.executeName !='sql工作台'&&temp.executeName !='上传sql脚本'">
            <el-input v-model="temp.executeParams" placeholder="参数格式:'param1','param2',..." />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="描述" prop="description" >
            <el-input v-model="temp.description" placeholder="请输入描述" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="temp.executeName=='上传jar包'">
          <el-form-item label="主类" prop="mainClass">
            <el-input v-model="temp.mainClass" placeholder="请输入主类" />
          </el-form-item>
        </el-col>
        <el-col :span="12" >
        <el-form-item label="任务状态" prop="status">
            <el-radio v-for="(item, index) in dictList('is_use')" :key="index" v-model="temp.status" :label="item.value">
              {{ item.label }}
            </el-radio> 
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="temp.executeName =='sql工作台'||temp.executeName=='shell工作台'">
        <SqlEditor ref="sqleditor" :value="temp.executeStatement" style="height: 300px; margin: 20px 0;"
          @changeTextarea="changeTextarea($event)"></SqlEditor>
      </el-row>
      <el-row v-if="temp.executeName =='上传jar包'||temp.executeName=='上传shell脚本'||temp.executeName=='上传sql脚本'">
        <el-upload class="upload-demo" :action="upUrl"
          :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="1"
          :on-exceed="handleExceed" :file-list="fileList" :on-change="handleChange" :accept="strType">
          <el-button size="small" type="primary">点击上传文件</el-button>
          <template #tip>
                <div class="el-upload__tip ">
                    <span>仅允许导入{{strType}}格式文件。</span>
                </div>
            </template>
        </el-upload>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        {{ $t('table.cancel') }}
      </el-button>
      <el-button type="primary" :loading="loading" @click="dialogStatus === 'create' ? createData() : updateData()">
        {{ $t('table.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createDataGovernance, updateDataGovernance, getDataGovernance,getTables } from '@/api/datagovernance/dataGovernance'
import SqlEditor from '@/components/SqlEditor'
import { listDataSource } from '@/api/metadata/sqlconsole'

export default {
  name: 'DataGovernanceForm',
  components: { SqlEditor },
  data() {
    return {
      temp: {
        executeType:'',
        executeName:'',
        executeStatement:'',
        status:1,
        mainClass:'',
        sourceId:'',
        description:'',
        fileName:'',
        sourceTableId:'',
        sourceTableName:'',
        targetTableId:'',
        targetTableName:''
      },
      textMap: {
        update: '编辑',
        create: '新建'
      },
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      sourceId: '',
      sourceOptions: [],//数据源数组
      executeStatement: '#!/bin/bash',
      fileList: [],
      strType:'',
      rules:{
        dataProcessName:[{required: true,message: '请输入名称', trigger: 'blur'}],
        executeName:[{required: true,message: '请选择执行类型', trigger: 'blur'}],
        sourceId:[{required: true,message: '请选择数据源', trigger: 'blur'}],
        mainClass:[{required: true,message: '请输入主类', trigger: 'blur'}],
        status:[{required: true,message: '请选择状态', trigger: 'blur'}],
        sourceTableName:[{required: true,message: '请选择来源表', trigger: 'blur'}],
        targetTableName:[{required: true,message: '请选择目标表', trigger: 'blur'}]
      },
      taleList:[],
      // upUrl:process.env.VUE_APP_BASE_API+'/datagovernance/DataGovernance/uploadFile'
      upUrl:'http://192.168.5.165:8082/datagovernance/DataGovernance/uploadFile'
    }
  },
  created() {
    this.getDataSourceList()
    
  },
  methods: {
    choseSourceTable(val){
        this.taleList.forEach(item=>{
          if(item.id==val){
            // this.temp.sourceTableName=item.tableName
            this.temp.sourceTableId=item.id
          }
        })
    },
    choseTargetTable(val){
      this.taleList.forEach(item=>{
          if(item.tableName==val){
            // this.temp.targetTableName=item.tableName
            this.temp.targetTableId=item.id
          }
        })
    },
    choseSource(id){
      getTables({sourceId:id}).then(res=>{
         
        if(res.data.code==200){
          this.taleList=res.data.data
        }
      })
    },
    handleChange(uploadFile){
      //  console.log(uploadFile,'111')
        this.temp.fileName=uploadFile.name
       setTimeout(()=>{
        this.temp.executeAddr=uploadFile.response.data.url
       })
          
    },
    restRule(){
      for(let key in this.rules){
        this.rules[key][0].required=true
      }
    },
  
    dictChose(){
     
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      console.log(files)
      // this.executeAddr=files
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    changeTextarea(val) {
      this.temp.executeStatement = val
    },
    getDataSourceList() {
      listDataSource().then(response => {
        if (response.data.code == 200) {
          this.sourceOptions = response.data.data
        }
      })
    },
    getList() {
      this.$emit('refreshList')
    },
    resetTemp() {
      this.loading = false
      this.temp = {
        id: undefined,
        dataProcessName: undefined,
        executeType: undefined,
        executeParams: undefined,
        mainClass: undefined,
        createBy: undefined,
        createDate: undefined,
        updateBy: undefined,
        updateDate: undefined,
        delFlag: undefined,
        remarks: undefined,
        tenantId: undefined,
        description: undefined,
        sourceId:undefined,
        executeAddr:undefined,
        executeName:undefined,
        executeStatement:undefined,
        status:undefined,
        fileName:undefined,
        sourceTableId:'',
        sourceTableName:'',
        targetTableId:'',
        targetTableName:''
      }
    },
    handleCreate() {
      this.fileList=[]
      this.resetTemp()
      this.dialogStatus = 'create'
      this.temp.status='1'
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          createDataGovernance(this.temp).then(response => {
            console.log(response)
            this.loading = false
            if (response.data.code === 0) {
              this.getList()
              this.dialogFormVisible = false
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    },
    choseType(data){
      this.restRule()
      this.strType=''
      if(data=='shell工作台'){
        if(this.dialogStatus=='create'){
          this.temp.executeStatement='#!/bin/bash'
        }
        this.rules.mainClass[0].required=false
        this.rules.sourceId[0].required=false
      }else if(data=='上传jar包'){
        this.strType='.jar'
        this.rules.sourceId[0].required=false
      }else if(data=='上传shell脚本'){
        this.strType='.sh'
        this.rules.sourceId[0].required=false
        this.rules.mainClass[0].required=false
      }else if(data=='上传sql脚本'){
        this.strType='.sql'
        this.rules.mainClass[0].required=false
      }else{
        this.rules.mainClass[0].required=false
      }
      this.temp.executeName=data
      this.dictList('executor_type').forEach(item=>{
        if(item.label==data){
          this.temp.executeType=item.value 
        }
      })
      this.$forceUpdate()
    },
    handleUpdate(id) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      getDataGovernance(id).then(response => {
        if (response.data.code === 0) {
          this.fileList=[]
          this.fileList.push({name:response.data.data.fileName,url:response.data.data.executeAddr})
          this.temp = response.data.data
          this.temp.executeStatement=response.data.data.executeStatement
          this.choseType(this.dictList('executor_type')[response.data.data.executeType].label) 
        } else {
          this.dialogFormVisible = false
          this.$message.error(response.data.msg)
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          updateDataGovernance(this.temp).then(response => {
            this.loading = false
            if (response.data.code === 0) {
              this.dialogFormVisible = false
              this.getList()
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    }
  }
}
</script>